'''
Created on 15.01.2012

@author: myaut
'''

import sys
import threading
import yappi

sys.path.append('../../lib')

from salsa.util.io import IOMaster, IORequestDead, IOFeederReply, IOFinishReply

from bench import bench_count_digits

rm = IOMaster(port=4010)

rm.dispatch_mode = IOMaster.DISPATCH_REQUEST

rm.hello_msg = 'Hello, what is your name?\n'
rm.start()

print 'Listening on port 4010'

exit_event = threading.Event()

def do_exit(rq):
    # print 'do_exit is called'
    exit_event.set()

yappi.start()

try:
    while True:
        in_request = rm.get()
        
        try:
            in_data = in_request.get()
            
            in_request.put('Hi, %s i am fine!\nAnd how do you do?\n' % in_data.strip())
            
            in_data = in_request.get()
            
            print in_data
            
            in_request.reg_finish_callback(do_exit)
            in_request.put(IOFeederReply(range(bench_count_digits).__iter__()))
            in_request.put(IOFinishReply())
            
            exit_event.wait()
            sys.exit()
            
        except IORequestDead, e:
            # print e.trace_buffer
            raise    
finally:
    yappi.print_stats()
    rm.stop()
